import { merge } from 'lodash';
import { get, post } from '@/utils/api-requester';
import { changePropertyName } from '@/utils/ObjectUtil';
import * as URLs from '@/constants/URLs';
import { GM } from '@/constants/ModelNamespaces';
import { showErrorMsg, showSuccessMsg } from '../../components/exception/GlobalMessage';



const url = URLs.GM;
//selectors
const getState = state => state[GM];

// interface GmState{
//     loading: boolean;
//         dataSource: Array<any>;
//         pagination: {
//             current: number,
//             pageSize: number,
//             total: number,
//             hideOnSinglePage: boolean,
//             showSizeChanger: boolean,
//             showQuickJumper: boolean,
//             size: string
//         };
//         querys: any;
//         gmAddView: {
//             loading: false,
//             visible: false,
//             currItemId: number
//         };
//         editPwdView: {
//             loading: false,
//             visible: false,
//             currId: number
//         }
// }
export default {
    namespace: GM,
    state: {
        dataSource: [],
        pagination: {
            current: 1,
            pageSize: 10,
            total: 0,
            hideOnSinglePage: true,
            showSizeChanger: true,
            showQuickJumper: true,
            size: 'small'
        },
        // sorter:{ field:'create_time', order:'descend' },
        querys: {},
        gmAddView: {
            visible: false,
            currItemId: null
        },
        editPwdView: {
            visible: false,
            currId: null
        }
    },
    effects: {
        'getGMs': function* ({ payload }, { put, call, select }) {
            try {
                // 1.准备请求参数.显示加载中
                let params = {};
                let final_pagination: any;
                let final_querys: any;

                // 如果请求参数为空,则使用store中存储的默认state来查询
                const state = yield select(getState);
                console.log('gmReducer default state', state);
                if (payload && payload.pagination && Object.entries(payload.pagination).length > 0) {
                    final_pagination = { current: payload.pagination.current, pageSize: payload.pagination.pageSize };
                } else {
                    final_pagination = { current: state.pagination.current, pageSize: state.pagination.pageSize };
                }
                if (payload && payload.querys && Object.entries(payload.querys).length > 0) {
                    final_querys = payload.querys;
                } else {
                    final_querys = state.querys;
                }

                params = { ...final_pagination, ...final_querys };
                changePropertyName(params, 'pageSize', 'page_size');
                console.log('加工好的请求参数GM query - request params:', params);

                const resp = yield call(get, url + '/query', params);
                // console.log('请求后台得到的结果', resp.data);
                const { error_code, data, pagination } = resp.data;
                if (error_code === 0) {
                    const payload = {
                        dataSource: data,
                        pagination: changePropertyName(pagination, 'page_size', 'pageSize'),
                        querys: final_querys,
                    };
                    // console.log('查询gm的结果:', payload);
                    yield put({ type: 'save', payload: payload });
                } else {
                    throw new Error(data);
                }
            } catch (e) {
                yield put({ type: 'save', payload: { error: e }, error: true });
                showErrorMsg(e);
            }
        },
        /**
         * 根据gm_id删除.
         */
        'delGMById': function* ({ payload }, { put, call }) {
            try {
                const id = payload;
                // console.log('请求删除gm的action:', action);
                const resp = yield call(post, url + '/delete_by_id/' + id);
                // console.log('saga到的gm结果 resp.data', resp.data);
                const { error_code, data } = resp.data;

                if (error_code === 0) {
                    yield put({ type: 'remove' });
                    //操作成功后,重新刷新页面的列表
                    yield put({ type: 'getGMs' });
                } else {
                    throw new Error(`${error_code},${data}`);
                }
            } catch (e) {
                yield put({ type: 'remove', payload: { error: e }, error: true });
                showErrorMsg(e);
            }
        },
        'add': function* ({ payload }, { put, call }) {
            try {
                const item = payload;
                // console.log('请求add gm的action:', action);

                yield put({ type: 'addGM', payload: { gmAddView: { loading: true } } });

                const resp = yield call(post, url + '/add', item);
                // console.log('saga到的gm结果', resp.data);
                const { error_code, data } = resp.data;

                if (error_code === 0) {
                    //操作成功后,重新刷新页面的列表
                    yield put({ type: 'getGMs' });
                } else {
                    throw new Error(data);
                }
            } catch (e) {
                yield put({ type: 'addGM', payload: { error: e}, error: true });
                showErrorMsg(e);
            }
        },
        'editPasswd': function* ({ payload }, { call, put }) {
            try {
                const item = payload;
                // console.log('the action for request edit gm pwd:', action);

                const resp = yield call(post, url + '/edit_passwd/' + item.id, { 'password': item.password });
                // console.log('saga到的gm结果', resp.data);
                const { error_code, data } = resp.data;

                if (error_code === 0) {
                    //解除提交按钮的loading状态.把待编辑项id置空.
                    yield put({ type: 'editGM', payload: { editPwdView: { visible: false, currId: null } } });
                } else {
                    throw new Error(data);
                }
            } catch (e) {
                yield put({ type: 'editGM', payload: { error: e }, error: true });
                showErrorMsg(e);
            }
        }
    },
    reducers: {
        save: (state, { payload })=>{
            const temp = merge({}, state, payload);
            temp.dataSource = payload.dataSource;//由于merge()对于数组只会合并,不会删除旧object中多余的元素,需要手动替换.
            return temp;
        },
        remove: (state, { payload })=>{
            return merge({}, state, payload);
        },
        toggleAddView: (state, { payload })=>{
            return merge({}, state, payload);
        },
        addGM: (state, { payload })=>{
            return merge({}, state, payload);
        },
        toggleEditPwdView: (state, { payload })=>{
            return merge({}, state, payload);
        },
        editGM: (state, { payload })=>{
            return merge({}, state, payload);
        },
    }
}
